import Taro from '@tarojs/taro'
import { URL_EXCHANGEBATTERY, URL_CREATEORDER, URL_WXPAYADVANSENCRYPT, WXAPPID, URL_WXPAYADVANS, URL_RENTBATTERY } from './../constants/SystemConstants';
import { WXRequest } from './../utils/WXRequest';
import { PAY_EXCHANGE_BATTERY_PENDING, PAY_EXCHANGE_BATTERY_REJECT, PAY_EXCHANGE_BATTERY_RESOLVE } from './../constants/pay';

const toExchangeBattery = (dispatch, eid) => {
  WXRequest(URL_EXCHANGEBATTERY, 'POST', {eid: eid}).then(res => {
    if (res.data.code === 0) {
      dispatch({
        type: PAY_EXCHANGE_BATTERY_RESOLVE,
        payType: 'huandian'
      })
      return
    }
    console.log('换电失败')
    console.log(res)
  }).catch(e => {
    dispatch({
      type: PAY_EXCHANGE_BATTERY_REJECT
    })
    console.error(e)
  })
}
// RentBattery
const toRentBattery = (dispatch, eid) => {
  WXRequest(URL_RENTBATTERY, 'POST', {eid: eid}).then(res => {
    if (res.data.code === 0) {
      dispatch({
        type: PAY_EXCHANGE_BATTERY_RESOLVE,
        payType: 'zudian'
      })
      return
    }
    console.log('换电失败')
    console.log(res)
  }).catch(e => {
    dispatch({
      type: PAY_EXCHANGE_BATTERY_REJECT
    })
    console.error(e)
  })
}

const createOrder = (orderData) => {
  return WXRequest(URL_CREATEORDER, 'POST', orderData)
}

export const payBattery = (eid, orderData, type) => async dispatch => {
  dispatch({
    type: PAY_EXCHANGE_BATTERY_PENDING
  })
  createOrder(orderData).then(res => {
    if (res.data.code > 0) return
    const orderId = res.data.id
    if (type === 'wallet') {
      // wallet payment
      toExchangeBattery(dispatch, eid)
    } else if( type === 'wechatpay' ) {
      // wechat payment
      wxPayAdvance(orderId).then(advanceRes => {
        wxPayAdvanceEncrypt(advanceRes.data.prepayId).then(advanceEncryptRes => {
          Taro.requestPayment({
            ...advanceEncryptRes.data,
            success: (res => {
              toExchangeBattery(dispatch, eid)
            })
          })
        })
      })
    } else if (type === 'zudian') {
      wxPayAdvance(orderId).then(advanceRes => {
        wxPayAdvanceEncrypt(advanceRes.data.prepayId).then(advanceEncryptRes => {
          Taro.requestPayment({
            ...advanceEncryptRes.data,
            success: (res => {
              toRentBattery(dispatch, eid)
            })
          })
        })
      })
    }
  }).catch(e => {
    console.error(e)
  })
}
// https://test.aixiang2018.com/api/v2/order-payments/weixin
const wxPayAdvance = (orderId) => {
  return WXRequest(URL_WXPAYADVANS, 'POST', { orderId: orderId, type: 0, appId: WXAPPID })
}

const wxPayAdvanceEncrypt = (prepayId) => {
  return WXRequest(URL_WXPAYADVANSENCRYPT(prepayId), 'POST', { appId: WXAPPID })
}

// export const payBattery = (eid, orderData) => async dispatch => {
  
  
// }